package com.zixun.controller;

import com.zixun.model.Bill;
import com.zixun.repository.BillRepository;
import com.zixun.service.BillService;
import com.zixun.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Basil on 16/8/27.
 */
@RestController
@RequestMapping("/api/bill")
public class BillWebApi {

    @Autowired
    private UserService userService;

    @Autowired
    private BillRepository billRepository;

    @Autowired
    private BillService billService;


    /**
     *
     * @api {GET} /api/bill/getBillList 获取流水列表
     * @apiName getBillList
     * @apiGroup bill
     * @apiVersion 0.0.1
     * @apiDescription 获取流水列表
     * @apiParam {String} userId 用户编号
     * @apiParam {Integer} countPerPage  显示数量
     * @apiParam {Integer} pageIndex 页码
     * @apiParam {Integer} billType 0:金钱明细  1:积分明细
     * @apiSuccessExample 返回值: HTTP/1.1 200 OK
     * {
     * "returnValue":【1:成功,2:参数错误,3:服务器异常,10:用户不存在 整型】,
     * "errMsg":【错误信息, 字符串】,
     * "data":
     *  [{
     *  "time":【时间, 长整型】
     *  "money":【金额,整型】
     *  "remark":【备注】
     *  "ioType":【0:收入，1:支出】
     *  }]
     * }
     * @return
     */
    @RequestMapping("getBillList")
    public Map<String,Object> getBillList(String userId,Integer billType,Integer pageIndex,Integer countPerPage){
        Map<String,Object> result = new HashMap<>();
        try {
            if(userId==null||pageIndex==null||countPerPage==null||billType==null){
                result.put("errMsg","参数错误");
                result.put("returnValue",2);
                return result;
            }
            if(!userService.isUserExist(Integer.valueOf(userId))){
                result.put("errMsg","用户不存在");
                result.put("returnValue",10);
                return result;
            }
            Page<Bill> billList= billService.findByUserIdPage(Integer.valueOf(userId),billType,pageIndex,countPerPage);
            List bills = new ArrayList<>();
            for(Bill bill :billList){
                Map billMap = new HashMap<>();
                billMap.put("time",bill.getCreateTime().getTime());
                billMap.put("remark",bill.getRemark());
                billMap.put("money",bill.getMoney());
                billMap.put("ioType",bill.getType());
                bills.add(billMap);
            }
            result.put("data",bills);
            result.put("returnValue",1);
            result.put("errMsg","成功");
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            result.put("errMsg","服务器异常");
            result.put("returnValue",3);
            return result;
        }
    }

}
